package server;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;


public class DatabaseUtility {
	protected final static String DATABASE_NAME = "SecGuard";
	protected final static String USER_NAME = "root";
	protected final static String PASSWORD = "papamama";
	
	/*
	 * Open an SQL connection
	 */
	public static Statement sqlStatement(){
		try{
			Class.forName("com.mysql.jdbc.Driver");
			Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/" + DATABASE_NAME, USER_NAME,PASSWORD);
			Statement stmt = (Statement) con.createStatement();
			return stmt;
		}
		catch(ClassNotFoundException cnfx){
			cnfx.printStackTrace();
			return null;
		}
		catch(SQLException sqlx){
			sqlx.printStackTrace();
			return null;
		}
	}
	
	/*
	 * Find a value of a field in  
	 */
	public static String search(String query, String field) throws SQLException{
		Statement stmt = sqlStatement();
		ResultSet rs = stmt.executeQuery(query);
		
		String queriedField = "";
		while (rs.next()){
			queriedField = rs.getString(field);
		}
		stmt.close();
		return queriedField;
	}
	
	/*
	 * Insert a record into the db
	 */
	public static int insert(String entry) throws Exception{
		Statement stmt = sqlStatement();
		int result = stmt.executeUpdate(entry);
		stmt.close();
		return result;
	}
	
	/*
	 * Query shared keys
	 */
	public static String findKey(String uid) throws SQLException{
		String keyQuery = "select * from SharedKeys where tag_uid = '" + uid + "'";
		String key = DatabaseUtility.search(keyQuery, "sharedKey");
		return key;
	}
}

